﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.Xml.Serialization;
using WebAnalyser.Library;

using log4net;
using log4net.Config;

using Microsoft.Samples;

namespace WebAnalyser.UI
{

    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private bool _alreadyFocused;

        public IntPtr Handle
        {
            get
            {
                var interopHelper = new WindowInteropHelper(this);
                return interopHelper.Handle;
            }
        }

        public MainWindow()
        {
            InitializeComponent();
            Common.MainWindow = this;
            Plugins.Instance.Init();
        }

        private void Window_Loaded(object sender, EventArgs e)
        {
            if (Settings.ReadValue("Main", "IsConfigured") == null || !String.Equals(Settings.ReadValue("Main", "IsConfigured"), "true"))
            {
                TaskDialog dialog = new TaskDialog();
                dialog.WindowTitle = "WebAnalyser";
                dialog.Content = "It seems it is the first time you run CSS Analyser. A configuration is required.";
                dialog.MainIcon = TaskDialogIcon.Warning;
                dialog.Show(Handle);
            }
        }

        private void urlTextBox_GotFocus(object sender, RoutedEventArgs e)
        {
            if (!_alreadyFocused)
            {
                urlTextBox.Text = "";
                _alreadyFocused = true;
            }
        }

        private void StartAnalyse()
        {
            Stopwatch sw = new Stopwatch();
            Web webRequest = new Web();
            Thread thread = new Thread(webRequest.Grab);
            Common.Threads.Add(thread);
            Common.AnalysisStatus = 0;
            Common.TotalLinks = 0;
            Common.MainWindow.Dispatcher.Invoke(DispatcherPriority.Normal,
                new Action(() =>
                    {
                        Common.MainWindow.urlTextBox.IsEnabled = false;
                        Common.MainWindow.startButton.IsEnabled = false;
                        Common.MainWindow.cancelButton.IsEnabled = true;
                        Data.Instance.CreateTable("zonebourse_com");
                        sw.Start();
                        thread.Start(Common.MainWindow.urlTextBox.Text);
                    }));
            thread.Join();
            sw.Stop();
            Common.Threads.Remove(thread);
            Common.MainWindow.Dispatcher.Invoke(DispatcherPriority.Normal,
                new Action(() =>
                    {
                        TaskbarManager.Instance.SetProgressState(TaskbarProgressBarState.NoProgress);
                        Common.MainWindow.resultProgressBar.Visibility = Visibility.Hidden;
                        Common.MainWindow.statusLabel.Visibility = Visibility.Hidden;
                        Common.MainWindow.urlTextBox.IsEnabled = true;
                        Common.MainWindow.startButton.IsEnabled = true;
                        Common.MainWindow.cancelButton.IsEnabled = false;
                        //if (!Common.CancellationPending)
                        //{
                            //new ResultWindow().Show();
                        //}
                        ResultWindow rw = new ResultWindow(sw.ElapsedMilliseconds);
                        rw.Show();
                    }));
        }

        private void startButton_Click(object sender, RoutedEventArgs e)
        {
            Regex urlRegex = new Regex(Common.UrlPattern, RegexOptions.Compiled);

            if (urlRegex.IsMatch(urlTextBox.Text))
            {
                TaskbarManager.Instance.SetProgressState(TaskbarProgressBarState.Indeterminate);
                Common.CancellationPending = false;
                Thread thread = new Thread(StartAnalyse);
                startButton.IsEnabled = false;
                resultProgressBar.IsIndeterminate = true;
                resultProgressBar.Visibility = Visibility.Visible;
                statusLabel.Visibility = Visibility.Visible;
                statusLabel.Content = "Preparing..";
                thread.Start();
            }
            else
            {
                TaskDialog dialog = new TaskDialog();
                dialog.WindowTitle = "WebAnalyser";
                dialog.Content = "The provided URL seems incorrect. Please, check and try again.";
                dialog.MainIcon = TaskDialogIcon.Error;
                dialog.Show(Handle);
                urlTextBox.Focus();
            }
        }

        private void Exit(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void Options(object sender, RoutedEventArgs e)
        {
            OptionsWindow optionsWindow = new OptionsWindow();
            optionsWindow.Owner = this;
            optionsWindow.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            optionsWindow.Show();
        }

        private void urlTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                startButton_Click(sender, e);
            }
        }

        private void cancelButton_Click(object sender, RoutedEventArgs e)
        {
            Common.CancellationPending = true;
            statusLabel.Content = "Cancelling..";
            cancelButton.IsEnabled = false;
        }

        private void About(object sender, RoutedEventArgs e)
        {
            TaskDialog dialog = new TaskDialog();
            dialog.WindowTitle = "WebAnalyser";
            dialog.MainIcon = TaskDialogIcon.Information;
            dialog.Content = "Version: " + Assembly.GetExecutingAssembly().GetName().Version;
            dialog.Show(Handle);
        }

        private void Window_Closing(object sender, CancelEventArgs e)
        {
            if (Common.Threads.Count != 0)
            {
                TaskDialog exitDialog = new TaskDialog();
                exitDialog.MainIcon = TaskDialogIcon.Warning;
                exitDialog.WindowTitle = "WebAnalyser";
                exitDialog.Content = "They are running jobs. Are you sure you want to exit?";
                TaskDialogCommonButtons commonButtons = 0;
                commonButtons |= TaskDialogCommonButtons.Yes;
                commonButtons |= TaskDialogCommonButtons.No;
                exitDialog.CommonButtons = commonButtons;
                int a = exitDialog.Show(Handle);
                if (a == 0x006)
                {
                    Common.CancellationPending = true;
                    Application.Current.Shutdown(1);
                }
                else
                {
                    e.Cancel = true;
                }
            }
            else
            {
                Application.Current.Shutdown(0);
            }
        }

        private void InsertSmtg(object data)
        {
            for (int i = 0; i < 1000; i++)
            {
                Data.Instance.InsertData("lu lal from threat" + data + "-" + i, "");
                Thread.Sleep(50);
            }
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            Data.Instance.CreateTable("stress_test");
            for (int i = 0; i < 100; i++)
            {
                Thread thread = new Thread(InsertSmtg);
                thread.Start(i);
            }
        }
    }
}